<template>
    <div class='file-upload' style='display:inline-block'>
        <div v-if='!pDel&&!uploadList.length' class="m-t-xxs">
            无文件
        </div>
        <Upload
                class='upload-btn'
                v-show='isAddBoxShow'
                style='display:inline-block'
                ref="upload"
                :default-file-list="defaultList"
                :show-upload-list="false"
                :multiple='pMultiple'
                :data="imageData"
                :before-upload="beforeUpload"
                :on-progress="onProgress"
                :on-success="onSuccess"
                :on-error="onError"
                :on-exceeded-size="handleMaxSize"
                type="drag"
                :max-size="this.pSize"
                :action="imageHost">
            <template v-if='!!$slots.default'>
                <!--
                    :on-format-error="handleFormatError"
                    :format="['jpg','jpeg','png']"
                -->
                <slot></slot>
            </template>
            <template v-if='!$slots.default&&pDel'>
                <Button type="ghost" icon="ios-cloud-upload-outline">上传文件</Button>
            </template>
        </Upload>
        <div class="file-upload-list" :class='{"have-file":uploadList.length}'>
            <table class="vm table table-hover m-b-none table-none-border">
                <tbody>
                    <tr  v-for="item in uploadList">
                        <td>
                            <template v-if="item.status === 'finished'">
                                {{item.alias}}
                            </template>
                            <template v-else>
                                <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
                            </template>
                        </td>
                        <td>
                            {{item.size_text}}
                        </td>
                        <td>
                            <div class="file-upload-list-cover" @click='downloadFile(item.name)'>
                                <a v-bind:href='downloadFile(item.name)' v-bind:download="item.name"><Icon type='ios-download-outline' ></Icon></a>
                            </div>
                        </td>
                        <td v-if='pDel'>
                            <div class="file-upload-list-cover">
                                <btn-confirm  p-message='你确定要删除此文件吗？' @on-change='handleRemove(item)'>
                                    <Icon type="ios-trash-outline"></Icon>
                                </btn-confirm>
                            </div>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
        <div v-if="!!pSubmit&&!!uploadList.length">
            <btn-confirm ref='confirm_upload' :p-submit='submitChange' p-message='您确认要保存吗？'></btn-confirm>
            <Button type="ghost" icon="ios-cloud-upload-outline" @click='confirmChange'>确认上传</Button>
        </div>
    </div>
</template>
<script>
    import Promise from 'promise'
    import serOss from 'serves/api-oss'
    import {img_whq} from 'filters/index'
    import {isArray,fileSizeCover} from '../../utils/index'
    import serConfig from '../../api-config'
    export default {
        name:"FileUpload",
        props:{
            pData:{
                type:[Array,Object]
            },
            pMultiple:{
                type:Boolean,
                default:false
            },
            pDir:{
                type:String,
                required:true
            },
            pSize:{
                type:Number,
                default:1024*10
            },
            pCount:{
                type:Number,
                default:1
            },
            pReplace:{
                type:Boolean,
                default:true
            },
            pDel:{
                type:Boolean,
                default:true
            },
            pSubmit:Function,
            pInfo:Object,
        },
        data () {
            return {
                imageData:{},
                defaultList:[],
                uploadList:[],
                imageHost:'',
                imgName:false,
                visible:false,
                progressNum:0,
            }
        },
        computed:{
            isMultiple(){
                return isArray(this.pData);
            },
            isAddBoxShow(){
                if(this.pCount == this.uploadList.length){
                    return false;
                }else {
                    return true;
                }
            }
        },
        mounted (){
            this.init(this.pData);
        },
        methods: {
            _hackUploadCpt(){
                this.$refs['upload'].handleStart = function(file) {
                    file.uid = Date.now() + this.tempIndex++;
                    const _file = {
                        status: 'uploading',
                        name: file.name,
                        size: file.size,
                        percentage: 0,
                        uid: file.uid,
                        showProgress: true,
                        //TODO start 增加别名,大小文本
                        alias:file.alias,
                        size_text:file.size_text
                        //TODO end 增加别名,大小文本
                    };
                    this.fileList.push(_file);
                }
            },
            confirmChange(){
                this.$refs['confirm_upload'].handleOpen(this.pInfo||this.info);
            },
            downloadFile(name){
                return  img_whq(name);
            },
            async submitChange(data){
                if(this.pSubmit){
                    const res = await this.pSubmit(data);
                    return res;
                }else {
                    return true;
                }
            },
            init(data){
                //TODO hack
                this._hackUploadCpt();
                this.defaultListInit(data);
                this.listInit();
            },
            defaultListInit(data){
                if(this.isMultiple){
                    if(data){
                        let arr = data.map((v,i)=>{
                            return {
                                alias: v.file_alias,
                                size: v.file_size,
                                size_text:fileSizeCover(v.file_size),
                                name: v.file_name
                            }
                        });
                        this.$set(this,'defaultList',arr)
                    }
                }else {
                    if(data&&typeof data == 'object'){
                        this.$set(this,'defaultList',[{
                            alias: data.file_alias,
                            size: data.file_size,
                            size_text:fileSizeCover(data.file_size),
                            name: data.file_name
                        }])
                    }
                }
            },
            listInit(){
                this.$nextTick(()=>{
                    if(this.$refs.upload){
                        this.$set(this,'uploadList',this.$refs.upload.fileList);
                    }
                });
            },
            async ossInit(){
                let res = await serOss.api({dir:this.pDir});
                this.$set(this, 'imageHost', res.host);
                this.imageData = res.data;
            },
            fileSizeText(size){
                return fileSizeCover(size);
            },
            async beforeUpload(data){
                let check;
                if(this.pCount!=-1){
                    check = this.uploadList.length < this.pCount;
                }else {
                    check = true;
                }
                if (!check) {
                    this.$Notice.warning({
                        title: '最多只能上传 '+this.pCount+' 个附件。'
                    });
                    return false
                }else {
                    await this.ossInit();
                    return new Promise((resolve)=>{
                        var file = new File([data],this.pDir+'_file_'+serOss.name() + data.name.match(/\.\w*?$/)[0],{type:data.type,size:data.size});/*data.name.match(/\.\w*?$/)[0]*/
                        file.alias = data.name;
                        file.size_text = fileSizeCover(data.size);
                        resolve(file)
                    });
                }
            },
            /*handleFormatError (file) {
                this.$Notice.warning({
                    title: '文件格式不正确',
                    desc: '文件 ' + file.name + ' 格式不正确，请上传 jpg、jpeg 或 png 格式的图片。'
                });
            },*/
            handleMaxSize (file) {
                this.$Notice.warning({
                    title: '超出文件大小限制',
                    desc: '文件 ' + file.alias + ' 太大，不能超过 '+fileSizeCover(this.pSize*1024.0)
                });
            },
            onProgress(event, file, fileList){
                if (event.total > 0) {
                    this.progressNum = parseInt(event.loaded / event.total * 100);
                }
            },
            onSuccess(response, file, fileList){
                /*TODO 后端oss配置问题，暂时去掉状态判断*/
                this.$emit('on-success',{dir:this.pDir,file:file.name,fileList:fileList});
                /*if(response.Status=='Ok'){
                    this.$emit('on-success',{dir:this.dir,name:file.name,files:fileList});
                }else {
                    this.$Notice.warning({
                        title: '上传错误',
                        desc: '文件上传错误，请重试。'
                    });
                }*/
            },
            onError(err){
                this.$Notice.warning({
                    title: '上传错误',
                    desc: '文件上传错误，请重试。'
                });
            },
            handleRemove (file) {
                // 从 upload 实例删除数据
                const fileList = this.$refs.upload.fileList;
                let index=-1;
                fileList.forEach((x,y)=>{
                    if(file.name==x.name){
                        index = y;
                    }
                });
                fileList.splice(index,1);
                this.listInit();
                this.$emit('on-delete',{dir:this.pDir,name:file.name,index:index,files:fileList});
            },
        },
        watch:{
            pData(newValue){
                this.init(newValue);
            }
        }
    }
</script>
<style lang="scss">
    .file-upload{
        text-align: right;
        line-height: 1;
    }
    .file-upload-list{
        display: block;
        border-radius: 4px;
        overflow: hidden;
        position: relative;
        margin-right: 4px;
        font-size: 14px;
        &.have-file{
            min-width: 150px;
        }
        td{
            word-wrap: break-word;
            word-break:break-all;
        }
    }
    .file-upload-list-cover{
        padding:2px 2px;
        border-radius: 4px;
        a,i{
            color:inherit;
            transition:none;
        }
        i{
            font-size: 24px;
            font-weight: bold;
            cursor: pointer;
        }
    }
    .table-none-border>tbody>tr:first-child>td{
        border-top:none;
    }
</style>
